package com.example.restatr.Atcivity.Movie.Fragment;

import android.media.MediaPlayer;
import android.os.Bundle;

import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.example.restatr.Atcivity.Main.MainActivity;
import com.example.restatr.Atcivity.Movie.Bean.MoviePreviewBean;
import com.example.restatr.R;
import com.example.restatr.Tools;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class MovieForeshowFragment extends Fragment {
    private ListView list;
    private List<MoviePreviewBean.RowsBean> moviePreviewBeans = new ArrayList<>();
    private StringBuilder mFormatBuilder = new StringBuilder();
    private Formatter mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
    private Timer timer;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_movie_foreshow, container, false);
        list = view.findViewById(R.id.list);
        GetMoviePreview();
        return view;
    }

    //获取电影预告数据
    private void GetMoviePreview() {
        new Thread(() -> {
            String get = Tools.Get("/prod-api/api/movie/film/preview/list", "");
            MoviePreviewBean moviePreviewBean = new Gson().fromJson(get, MoviePreviewBean.class);
            if (moviePreviewBean.getRows() != null) {
                moviePreviewBeans.addAll(moviePreviewBean.getRows());
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        list.setAdapter(new adapter());
                    });
                }
            }
        }).start();
    }

    //获取视频进度转为时长 MediaController类里拔下来的
    private String stringForTime(int timeMs) {
        int totalSeconds = timeMs / 1000;

        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;

        mFormatBuilder.setLength(0);
        if (hours > 0) {
            return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
        } else {
            return mFormatter.format("%02d:%02d", minutes, seconds).toString();
        }
    }

    //动态更新进度条
    private void SetProgressBar(ProgressBar mProgress, VideoView video, TextView startText) {
        timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        int pos = video.getCurrentPosition() / 1000;//获取视频当前位置
                        mProgress.setProgress(pos);//设置进度条当前进度
                        startText.setText(stringForTime(video.getCurrentPosition()));//当前播放时间
                        Log.d("TAG", "run: " + video.getCurrentPosition() / 1000);
                    }
                });
            }
        };
        timer.schedule(timerTask, 1000, 1000);
    }

    //播放视频
    private void VideoPlayer(VideoView video, ImageView PlayerAndPause, ProgressBar mProgress, TextView startTime) {
        video.start();
        PlayerAndPause.setImageResource(R.drawable.ic_round_pause_24);
        mProgress.setMax(video.getDuration() / 1000);
        SetProgressBar(mProgress, video, startTime);
    }

    class adapter extends BaseAdapter {

        @Override
        public int getCount() {
            return moviePreviewBeans.size();
        }

        @Override
        public Object getItem(int position) {
            return moviePreviewBeans.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = getLayoutInflater().inflate(R.layout.foreshow_item_layout, null);
            VideoView video = convertView.findViewById(R.id.video);
            CardView see = convertView.findViewById(R.id.see);
            LinearLayout like = convertView.findViewById(R.id.like);
            ImageView likeImg = convertView.findViewById(R.id.likeImg);
            TextView name = convertView.findViewById(R.id.name);
            ImageView cover = convertView.findViewById(R.id.cover);
            TextView cardName = convertView.findViewById(R.id.card_name);
            TextView showDate = convertView.findViewById(R.id.showDate);
            RelativeLayout jdtLL = convertView.findViewById(R.id.jdt_LL);
            TextView PosTime = convertView.findViewById(R.id.startTime);
            ImageView PlayerAndPause = convertView.findViewById(R.id.PlayerAndPause);
            ProgressBar mProgress = convertView.findViewById(R.id.bar);
            TextView endTime = convertView.findViewById(R.id.endTime);
            ImageView player = convertView.findViewById(R.id.player);
            TextView nullText = convertView.findViewById(R.id.nullText);

            name.setText(moviePreviewBeans.get(position).getName() + " 电影预告片");
            Glide.with(getActivity())
                    .load(Tools.ip + moviePreviewBeans.get(position).getCover())
                    .transform(new RoundedCorners(15))
                    .into(cover);
            cardName.setText(moviePreviewBeans.get(position).getName());
            showDate.setText(moviePreviewBeans.get(position).getPlayDate());
            //设置视频路径
            if (moviePreviewBeans.get(position).getVideo() != null) {
                video.setVideoPath(Tools.ip + moviePreviewBeans.get(position).getVideo());
            } else {
                nullText.setVisibility(View.VISIBLE);
                player.setVisibility(View.GONE);
            }
            //视频播放完成监听事件
            video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    PlayerAndPause.setImageResource(R.drawable.ic_round_play_arrow_24);
                    timer.cancel();
                }
            });
            //设置展示画面
            video.seekTo(1);
            //播放按钮监听
            player.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    jdtLL.setVisibility(View.VISIBLE);
                    player.setVisibility(View.GONE);
                    endTime.setText(stringForTime(video.getDuration()));
                    VideoPlayer(video, PlayerAndPause, mProgress, PosTime);
                }
            });
            //暂停，播放，进度条监听
            PlayerAndPause.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (video.isPlaying()) {
                        Log.d("TAG", "onClick: 点击了暂停");
                        video.pause();
                        PlayerAndPause.setImageResource(R.drawable.ic_round_play_arrow_24);
                        timer.cancel();
                    } else {
                        Log.d("TAG", "onClick: 点击了播放");
                        VideoPlayer(video, PlayerAndPause, mProgress, PosTime);
                    }
                }
            });
            final boolean[] posLike = {false};
            //想看点击事件
            like.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!posLike[0]) {
                        new Thread(() -> {
                            try {
                                String post = Tools.Post("/prod-api/api/movie/film/like/" + moviePreviewBeans.get(position).getId(), MainActivity.sp.getString("token", ""), "");
                                JSONObject jx = new JSONObject(post);
                                int code = jx.getInt("code");
                                String msg = jx.getString("msg");

                                if (getActivity() != null) {
                                    getActivity().runOnUiThread(() -> {
                                        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                                        if (code == 200) {
                                            likeImg.setBackgroundResource(R.drawable.ic_baseline_favorite_24);
                                            posLike[0] = true;
                                        }
                                    });
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }).start();
                    }
                }
            });

            return convertView;
        }
    }
}